package dk.kapetanovic.jaft.transaction.fac;

import java.io.File;
import java.io.IOException;
import java.util.Arrays;

import dk.kapetanovic.jaft.exception.TransactionException;
import dk.kapetanovic.jaft.log.Journal;
import dk.kapetanovic.jaft.log.JournalImpl;
import dk.kapetanovic.jaft.log.OutputJournal;
import dk.kapetanovic.jaft.transaction.Transaction;
import dk.kapetanovic.jaft.transaction.TransactionImpl;
import dk.kapetanovic.jaft.transaction.TransactionManager;


public class OutputTransactionFactory implements TransactionFactory {
	
	private TransactionManager tm;
	private int unique = 1;
	private File dir;

	public OutputTransactionFactory(TransactionManager tm, File journalDir) {
		this.tm = tm;
		this.dir = journalDir;
		unique = getFirst(journalDir) + 1;
	}

	public OutputTransactionFactory(File journalDir) {
		this.dir = journalDir;
	}

	@Override
	public Transaction createTransaction() throws TransactionException {
		try {
			File file;
			do {
				file = new File(dir, getName(unique));
				unique++;
			} while(file.exists());
			
			Journal journal = new OutputJournal(new JournalImpl(), file);
			return new TransactionImpl(tm, journal);
		}
		catch (IOException e) {
			throw new TransactionException(e);
		}
	}

	@Override
	public void setTransactionManager(TransactionManager tm) {
		this.tm = tm;
	}
	
	private String getName(int n) {
		return "transaction_journal-" + n + ".dat";
	}
	
	private int getFirst(File journalDir) {
		File[] files = journalDir.listFiles(new JournalFilter());
		if(files.length == 0)
			return 0;
		
		Arrays.sort(files);
		String name = files[files.length - 1].getName();
		
		int i = name.indexOf("-");
		int j = name.indexOf(".dat");
		return Integer.parseInt(name.substring(i + 1, j));
	}
}
